import { getCookieValue, setCookieValue } from '@/utils/utils'
import { LANGS, getLanguage } from '@/lang'
import { changeLanguage } from '@/api/settings'
import { getToken } from '@/utils/auth/token'
import { getAll } from '@/api/account'
import defaultSettings from '@/settings'

const state = {
  app: {
    siteName: defaultSettings.title,
    description: ""
  },
  token: getToken(),
  sidebar: {
    opened: getCookieValue('sidebarStatus') ? !!+getCookieValue('sidebarStatus') : true,
    withoutAnimation: false
  },
  device: 'desktop',
  language: getLanguage(),
  size: getCookieValue('size') || 'medium'
}

const mutations = {
  SET_APP: (state, app) => {
    state.app.siteName = app.siteName || defaultSettings.title
    state.app.description = app.description
  },
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      setCookieValue('sidebarStatus', 1)
    } else {
      setCookieValue('sidebarStatus', 0)
    }
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    setCookieValue('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SET_LANGUAGE: (state, language) => {
    state.language = language
    setCookieValue(
      'Abp.Localization.CultureName',
      language,
      new Date(new Date().getTime() + 5 * 365 * 86400000),
      '/'
    );
  },
  SET_SIZE: (state, size) => {
    state.size = size
    setCookieValue('size', size)
  }
}

const actions = {
  getAll({ commit }) {
    return new Promise((resolve, reject) => {
      getAll().then((data) => {
        // commit('SET_LANGUAGE', data.localization.currentLanguage.name)
        // commit('SET_APP', { siteName: data.setting.values['Site.SiteName'], description: "" })
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  closeSideBar({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  setLanguage({ commit, state }, lang) {
    return new Promise((resolve, reject) => {
      var language = lang
      var languageName = LANGS[lang].abp
      if (state.token) {
        changeLanguage({ languageName: languageName.trim() }).then(() => {
          commit('SET_LANGUAGE', language)
          resolve()
        }).catch(error => {
          reject(error)
        })
      } else {
        commit('SET_LANGUAGE', language)
        resolve()
      }
    })
  },
  setSize({ commit }, size) {
    commit('SET_SIZE', size)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
